const ejsexcel = require('ejsexcel')
const fs = require('fs')
const util = require('util')
const log4js = require('./log4j')
const readFileAsync = util.promisify(fs.readFile)
const writeFileAsync = util.promisify(fs.writeFile)
const path = require('path')
const Formula = require('../modules/formula')
const moment = require('moment')
/**
 * 导出文件
 * @param {Array} data:数据源
 * @param {String} name:店铺名
 * @param {String} user:人员名称
 * @param {String} count:单量
 * */
async function exportTabe(data, name, user, count) {
  let paurl = path.join(__dirname, '../views')
  const testFolder = `${paurl}/input`
  let fileName = `${name}.xlsx`
  fs.readdirSync(testFolder).forEach((file) => {
    if (file == fileName) {
      fileName = `${name}+${user}+${count}.xlsx`
    }
  })
  try {
    let Aarray = []
    const gs = await Formula.findOne({ name: name })
    Aarray.push(data)
    if (gs != null) {
      Aarray.push(gs)
    } else {
      Aarray.push({})
    }
    //获得Excel模板的buffer对象
    const exlBuf = await readFileAsync(`${paurl}/tempale.xlsx`)
    //用数据源(对象)data渲染Excel模板
    //cachePath 为编译缓存路径, 对于模板文件比较大的情况, 可显著提高运行效率, 绝对路径, 若不设置, 则无缓存
    const exlBuf2 = await ejsexcel.renderExcel(exlBuf, Aarray, {
      cachePath: __dirname + '/cache/',
    })
    await writeFileAsync(`${paurl}/input/${fileName}`, exlBuf2)
    log4js.mark(`导出成功:${name}=>${user}=>${count}`)
  } catch (error) {
    log4js.mark(`导出失败=>${error}=>${name}=>${user}=>${count}`)
    return Promise.reject(error)
  }
}

module.exports = exportTabe
